package com.fsquare.dao.invoice;

import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.broadleafcommerce.common.persistence.EntityConfiguration;
import org.hibernate.ejb.QueryHints;
import org.springframework.stereotype.Service;

import com.fsquare.domain.invoice.Invoice;

@Service("fsquareInvoiceDao")
public class InvoiceDaoImpl implements InvoiceDao{

	@PersistenceContext(unitName="blPU")
    protected EntityManager em;

    @Resource(name="blEntityConfiguration")
    protected EntityConfiguration entityConfiguration;
	
	@Override
	public Invoice saveInvoice(Invoice invoice) {
		return em.merge(invoice);
	}

	@Override
	public List<Invoice> readAllInvoices() {
		Query query = em.createNamedQuery("ALL_INVOICES");
        query.setHint(QueryHints.HINT_CACHEABLE, true);
        return query.getResultList();
	}

	@Override
	public Invoice readInvoiceById(Long invoiceId) {
		Query query = em.createNamedQuery("INVOICE_BY_ID");
		query.setParameter("id", invoiceId);
//        query.setHint(QueryHints.HINT_CACHEABLE, true);
        return (Invoice)query.getSingleResult();
	}

	@Override
	public void deleteInvoice(Invoice invoice) {
		em.remove(invoice);
		
	}

	@Override
	public Invoice create() {
        return (Invoice)entityConfiguration.createEntityInstance(Invoice.class.getName());

	}

	@Override
	public Invoice readInUseInvoice() {
		Query query = em.createNamedQuery("IN_USE_INVOICE");
        query.setHint(QueryHints.HINT_CACHEABLE, true);
        return (Invoice)query.getSingleResult();
	}

}
